package com.yangxd.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangxd.handler.BusinessException;
import com.yangxd.response.ResultCode;
import com.yangxd.system.entity.TbUser;
import com.yangxd.system.enums.UserStatusEnum;
import com.yangxd.system.enums.UserTypeEnum;
import com.yangxd.system.mapper.TbUserMapper;
import com.yangxd.system.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yangxd
 * @since 2021-02-26
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<TbUser> findPageUser(Page<TbUser> page, QueryWrapper<TbUser> wrapper) {
        return this.baseMapper.findPageUser(page,wrapper);
    }

    /**
     * 添加用户
     *
     * @param tbUser
     */
    @Override
    public void addUser(TbUser tbUser) {
        //判断是否重复添加
        String username = tbUser.getUsername();
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Integer count = this.baseMapper.selectCount(queryWrapper);
        if(count != 0) {
            //抛出用户已存在的异常
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        String salt = UUID.randomUUID().toString().substring(0,32);
        tbUser.setSalt(salt);
//        tbUser.setCreateTime(new Date());
//        tbUser.setModifiedTime(new Date());
        //使用spring security自带的密码加密策略
        tbUser.setPassword(passwordEncoder.encode(tbUser.getPassword()));
        //设置用户类型
        tbUser.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //设置状态
        tbUser.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        //设置是否删除
        tbUser.setDeleted(false);
       // tbUser.setStatus();
        this.baseMapper.insert(tbUser);
    }

    /**
     * 根据username查询用户
     *
     * @param username
     */
    @Override
    public TbUser selectByName(String username) {
        return this.baseMapper.selectByName(username);
    }
}
